const app = getApp();
const userInfo = wx.getStorageSync('userinfo');
const {
  htmlDecode
} = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabListConst: [
      {
        name: '详情',
        tag: "",
        params: {
          status: '1'
        }
      },
      {
        name: '治理流程 ',
        tag: "",
        params: {
          status: '2'
        }
      },
    ],
    tabIndex: 0,
    flowStatusArray: ['提出隐患','跟进中','已完成','已通过','已退回','申请延期','已转交','已作废'],
    flowTypeArray: ['指派责任部门','指派整改人','整改隐患','整改后审核','延期审核'],
    colorArray: ['green', 'blue','green', 'green', 'red','blue','orange','gray'],

    flowList: [],
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    risk: {},
    deadlineArray: ['立即', '七天', '十五天', '一个月'],
    riskTypeArray: ['职业卫生', '消防安全', '环境保护', '安防管理', '安全生产'],
    nodeArray: ['申请退回', '指派责任部门', '指派处理', '隐患排除中', '整改后审核', '闭环'],
    riskLevelArray: ['一般', '重大'],
    deptList: [],
    staffList: [],
    fixImgList: [],
    afterPic: null,
    riskId: null,
    dealFlag: null,
    ssoFlag: null,
    user: userInfo.siocCnName,
    applyDate: new Date().toISOString().substring(0, 10),
    flowType: null,
    flowId: null,
    deptIndex: null,
    staffIndex: null,
    deadlineIndex: null,
    apply: false,
    fixDone: false,
    bigSearchShow: false,
    bigSearchType: "",
    corrector: "",
    dutyDept: "",
    searchDataList: [],
    selfDept: false,
    bigSearchShowType: '',
    personnelIndex: '',
    personnelList: ['AS PM11', 'AS PM12', 'AS PM13', '复卷机'],
    isShengChanBu: false,
    handoverFlag: false
  },
  tabChange(e) {
    this.setData({
      tabIndex: e.detail.tabIndex
    })
  },
  //催办
  push() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/rmStaff/wx/push?riskId=' + that.data.riskId,
      method: 'POST',
      success: function (res) {
        console.log('操作成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },

  getAllDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取所有部门信息:', res.data);
        var data = res.data;
        that.setData({
          deptList: data.data
        })
      }
    });
  },

  getStaffByDept: function (dutyDept) {
    return new Promise((reslove, reject) => {
      var that = this;
      wx.request({
        url: that.data.baseUrl + '/staffInfo/wx/getStaffByDept?dept=' + dutyDept,
        method: 'GET',
        header: {
          'Content-Type': 'application/json' // 请求头  
        },
        success(res) {
          console.log('获取部门员工信息:', res.data);
          var data = res.data;


          that.setData({
            staffList: data.data,
          })

          return reslove(data.data)

        }
      });
    })

  },

  searchSelect(e) {

    // if(e.detail.name==''){
    //   return
    // }
    const params = {}
    params[this.data.bigSearchType == 'staff' ? 'corrector' : 'dutyDept'] = e.detail.name || ""
    if (this.data.bigSearchShowType == 'dept') {
      Object.assign(params, {
        isShengChanBu: e.detail.name == '生产部'
      })
    }
    this.setData({
      ...params
    })


  },

  DateChange: function (e) {
    this.setData({
      applyDate: e.detail.value
    })
  },
  //申请延期
  applyPostpone: function () {
    this.setData({
      apply: !this.data.apply
    })
  },
  //取消申请延期
  cancelApply: function () {
    this.setData({
      apply: false
    })
  },
  //转交
  handover: function () {
    this.setData({
      handoverFlag: true
    })
    this.getStaffBySapId();
  },
  //取消转交
  cancelHandover: function () {
    this.setData({
      handoverFlag: false
    })
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.fixImgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            fixImgList: this.data.fixImgList
          })
        }
      }
    })
  },
  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.fixImgList.length != 0) {
              that.setData({
                fixImgList: that.data.fixImgList.concat(tempArray)
              })
            } else {
              that.setData({
                fixImgList: tempArray
              })
            }
          }
        })
      }
    })
  },
  getRiskInfo: function (riskId) {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/rmStaff/wx/getRiskInfo?riskId=' + riskId,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'userNo': userInfo.siocSapNo // 请求头 
      },
      success(res) {
        console.log('获取隐患详情:', res.data);
        var data = res.data;

        data.data.location = htmlDecode(data.data.location)
        data.data.content = htmlDecode(data.data.content)
        data.data.suggest = htmlDecode(data.data.suggest)

        that.setData({
          risk: data.data,
          imgList: data.data.imgList,
          fixImgList: data.data.fixImgList
        });
        if (1 == that.data.flowType) {
          that.getStaffByDept(data.data.dutyDept);
        }
      }
    });
  },
  getRIskFlow: function (riskId) {
    var that = this;
    wx.request({
      url: that.data.baseUrl+'/rmStaff/wx/getRiskFlow?riskId='+riskId,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头
      },
      success(res) {
        console.log('获取所隐患流程:', res.data);
        var data=res.data;
        that.setData({
          flowList: data.data
        })
      }
    });
  },

  chooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            // 上传成功，做一些处理
            let json = JSON.parse(res.data);
            console.log('上传图片结果', res.data)
            that.setData({
              afterPic: that.data.fileUrl + json.fileName,
              fixDone: true
            })
          }
        })
      }
    })
  },

  deptChange: function (e) {
    console.log('部门选择改变，携带值为', e)
    this.setData({
      deptIndex: e.detail.value
    })
  },

  staffChange: function (e) {
    console.log('部门选择改变，携带值为', e)
    this.setData({
      staffIndex: e.detail.value
    })
  },

  selfDeptChange(e) {
    this.setData({
      selfDept: e.detail.value
    })
    if (e.detail.value) {
      this.getStaffBySapId();
    }
  },

  submitForm(e) {
    var that = this;
    const formData = e.detail.value;
    var errMsg = "";
    var endPoint = "";
    // 指派责任部门
    if (that.data.flowType == 0) {
      if (!formData.dutyDept && !that.data.selfDept) {
        errMsg = errMsg + "责任部门不能为空;";
      }
      if (!formData.corrector && that.data.selfDept) {
        errMsg = errMsg + "整改人不能为空;";
      }
      if (!formData.deadline && that.data.selfDept) {
        errMsg = errMsg + "整改期限不能为空;";
      }
      if (that.data.isShengChanBu && !formData.dutyDeptPa) {
        errMsg = errMsg + "Personnel Area不能为空;";
      }
      formData.sapId = userInfo.siocSapNo;
      formData.selfDept = that.data.selfDept;
      endPoint = "/rmStaff/wx/passPropose";
    }
    //指派整改人
    if (that.data.flowType == 1) {
      if (!formData.corrector) {
        errMsg = errMsg + "整改人不能为空;";
      }
      if (!formData.deadline) {
        errMsg = errMsg + "整改期限不能为空;";
      }
      endPoint = "/rmStaff/wx/assign";
      formData.dutyDept = that.data.risk.dutyDept;
    }
    //整改
    if (that.data.flowType == 2) {
      if (that.data.apply) {  //申请延期
        if (!formData.reason) {
          errMsg = errMsg + "延期原因不能为空;";
        }
        if (!formData.provisionalMeasures) {
          errMsg = errMsg + "临时措施不能为空;";
        }
        endPoint = "/rmStaff/wx/applyPostpone";
        formData.userSapId = userInfo.siocSapNo;
      } else if (that.data.handoverFlag) {  //转交 
        formData.dutyDept = that.data.risk.dutyDept;
        if (!formData.corrector) {
          errMsg = errMsg + "整改人不能为空;";
        }
        endPoint = "/rmStaff/wx/handOver";
      } else { //整改完成
        formData.fixImgList = that.data.fixImgList;
        if (formData.fixImgList.length < 1) {
          errMsg = errMsg + "整改图片不能为空;";
        }
        endPoint = "/rmStaff/wx/fixDone";
      }
    }
    formData.handleBy = that.data.user;
    if (errMsg.length > 0) {
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }
    // 向服务器提交表单数据
    console.log('form发生了submit事件，携带数据为：', formData);
    wx.request({
      url: that.data.baseUrl + endPoint,
      method: 'POST',
      data: formData,
      success: function (res) {
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/risk-list/risk-list'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },

  refuse() {
    var that = this;
    wx.showModal({
      editable: true, //显示输入框
      placeholderText: '输入退回原因', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          console.log(res.content) //用户输入的值
          if(!res.content){
            wx.showModal({
              title: '提示',
              content: "退回原因不能为空",
              showCancel: false
            })
            return;
          }
          wx.request({
            url: that.data.baseUrl + '/rmStaff/wx/refuse',
            method: 'POST',
            data: {
              'riskId': that.data.riskId,
              'flowId': that.data.flowId,
              'remark': res.content,
              'flowType': that.data.flowType,
              'handleBy': that.data.user
            },
            success: function (res) {
              console.log('表单提交成功', res);
              if (200 == res.data.code) {
                wx.showModal({
                  title: '提示',
                  content: res.data.msg,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      wx.reLaunch({
                        url: '/pages/risk-list/risk-list'
                      })
                    }
                  }
                })
              } else {
                wx.showToast({
                  title: '提交失败',
                  icon: 'none'
                });
              }
            },
            fail: function (err) {
              console.error('表单提交失败', err);
              wx.showToast({
                title: '表单提交失败',
                icon: 'none'
              });
            }
          });
        } else {
          console.log('用户点击了取消')
        }
      }
    })
  },
  deadlineChange: function (e) {
    console.log('期限选择变化，携带值为', e.detail.value)
    this.setData({
      deadlineIndex: e.detail.value
    })
  },
  ViewImage(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.imgList) {
      urls.push(this.data.fileUrl + this.data.imgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  ViewImage2(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.fixImgList) {
      urls.push(this.data.fileUrl + this.data.fixImgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  passAudit() {
    var that = this;
    var tempFlowType = that.data.flowType;
    var endPoint = '';
    if (4 == tempFlowType) {
      endPoint = 'passPostpone';
    }
    if (3 == tempFlowType) {
      endPoint = 'passProposeAudit';
    }
    wx.request({
      url: that.data.baseUrl + '/rmStaff/wx/' + endPoint,
      method: 'POST',
      data: {
        'riskId': that.data.riskId,
        'flowId': that.data.flowId,
        'handleBy': that.data.user
      },
      success: function (res) {
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/risk-list/risk-list'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '提交失败',
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },
  goRiskFlow() {
    var that = this;
    wx.navigateTo({
      url: '/pages/risk-flow/risk-flow?riskId=' + that.data.riskId,
    })
  },

  personnelChange(e) {
    this.setData({
      personnelIndex: e.detail.value
    })
  },

  async doBigSearchShow(e) {
    console.log('e', e);
    const tempArray = [];
    const typeMethods = {
      staff: async () => {
        let staffList = []
        if (this.data.staffList == 0) {
          staffList = await this.getStaffByDept(this.data.dutyDept)
        } else {
          staffList = this.data.staffList
        }
        if (staffList.length == 0) {
          wx.showToast({
            title: '暂无整改人指派',
            icon: 'none'
          });
          return;
        } else {
          staffList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      },

      dept: () => {
        if (this.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    await typeMethods[e.currentTarget.dataset.type]();
    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      bigSearchShowType: e.currentTarget.dataset.type,

      searchDataList: tempArray
    })
  },

  getStaffBySapId: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/staffInfo/wx/getStaffBySapId?sapId=' + userInfo.siocSapNo,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取部门员工信息:', res.data);
        var data = res.data;
        that.setData({
          staffList: data.data,
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getRiskInfo(options.riskId);
    this.getRIskFlow(options.riskId);
    this.setData({
      riskId: options.riskId,
      dealFlag: options.dealFlag,
      flowType: options.flowType,
      flowId: options.flowId
    });
    if (options.flowType == 0) {
      this.getAllDept();
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})